package com.android.myqimc;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	//设置值的配置文件
	public static String fileName = "mc.ini";
	//上次MC第一天的日期
	public static String mcdate_key = "mcdate";
	private String mcdate_value = "";
	//MC周期
	public static String period_key = "period";
	private String period_value = "28";
	//每日提醒时间
	public static String remind_key = "remind";
	private String remind_value = "1200";
	
	private TextView txt_premcval;//上次MC第一天
	private TextView txt_nextmcval;//预计下次MC日期
	private TextView txt_leftndays;//距离现在还有X天
	private TextView txt_expnextodayval;//预计下次排卵日
	private Button btn_settings;//设置按钮
	private Button btn_wdd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		txt_premcval = (TextView) this.findViewById(R.id.txt_premcval);
		txt_nextmcval = (TextView) this.findViewById(R.id.txt_nextmcval);
		txt_leftndays = (TextView) this.findViewById(R.id.txt_leftndays);
		txt_expnextodayval = (TextView) this.findViewById(R.id.txt_expnextodayval);
		btn_settings = (Button) this.findViewById(R.id.btn_settings);
		btn_wdd = (Button) this.findViewById(R.id.btn_wdd);
		
		//点击设置按钮跳转到深圳页面
		btn_settings.setOnClickListener(new Button.OnClickListener()
		{
			@Override
			public void onClick(View arg0){//直接实现接口函数
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, Settings.class);//设置跳转activity
				Bundle bundle = new Bundle();
				bundle.putString(mcdate_value, mcdate_value);//上次MC第一天的日期
				bundle.putString(period_key, period_value);
				bundle.putString(remind_key, remind_value);
				intent.putExtras(bundle);//存储跨activity数据
				startActivity(intent);
				finish();
			}
			
		});
		
		btn_wdd.setOnClickListener(new Button.OnClickListener()
		{
			public void onClick(View arg0){
				Toast.makeText(getApplicationContext(), R.string.msg_wdd, Toast.LENGTH_SHORT).show();
			}
		});
		
		//检查文件mc.ini是否存在
	    checkFile();
	    
	    //计算相关日期
	    calDate();
	}//end onCreate
	
	//文件存在检查
	  private void checkFile()
	  {
	    boolean isExit = true;

	    FileOutputStream fos = null;
	    try
	    {
	      openFileInput(fileName);//打开mc.ini文件
	    } catch (FileNotFoundException e)
	    {
	      isExit = false;
	    }
	    
	    if (!isExit)//文件不存在
	    {
	      try
	      {
	        fos = openFileOutput(fileName, MODE_WORLD_WRITEABLE);//创建mc.ini文件，可写模式
	        BufferedOutputStream bos = new BufferedOutputStream(fos);//创建文件输出缓冲流

	        //获取系统日期，并将该值赋给上次MC第一天
	        mcdate_value = DateUtil.getDateTime("yyyyMMdd", System
	            .currentTimeMillis());
	        String txt = mcdate_key + "=" + mcdate_value;
	        bos.write(txt.getBytes());//以字节流的形式写入配置文件
	        //默认周期为28
	        bos.write(new String("\n").getBytes());//换行
	        txt = period_key + "=" + period_value;
	        bos.write(txt.getBytes());
	        //提醒时间为中午12点
	        bos.write(new String("\n").getBytes());
	        txt = remind_key + "=" + remind_value;
	        bos.write(txt.getBytes());

	        bos.close();
	        fos.close();

	      } catch (FileNotFoundException e)//文件未找到，创建失败
	      {
	        e.printStackTrace();
	      } catch (IOException e)//输入输出错误
	      {
	        e.printStackTrace();
	      }
	    }
	    //读取mc.ini的值
	    Properties p = new Properties();
	    try
	    {
	      p.load(openFileInput(fileName));
	      mcdate_value = p.getProperty(mcdate_key);
	      period_value = p.getProperty(period_key);
	      remind_value = p.getProperty(remind_key);
	    } catch (FileNotFoundException e)
	    {
	      e.printStackTrace();
	    } catch (IOException e)
	    {
	      e.printStackTrace();
	    }
	  }//end checkFile()

	  private void calDate()
	  {

	    String format = "yyyy.MM.dd";

	    //上次MC第一天的日期
	    txt_premcval.setText(DateUtil
	        .getNextDate(mcdate_value, 0, format));

	    //预计下次MC日期
	    txt_nextmcval.setText(DateUtil.getNextDate(mcdate_value, Integer
	        .parseInt(period_value), format));

	    //距离现在还有N天
	    String nDate = DateUtil.getNextDate(mcdate_value, Integer
	        .parseInt(period_value), "yyyyMMdd");
	    int days = DateUtil.computerDiffDate(DateUtil
	        .getDateTime(nDate), System.currentTimeMillis());
	    String text = "";
	    if (days >= 0)
	    {
	      text += getResources().getString(R.string.strMessage5);
	      text += days;
	      text += getResources().getString(R.string.strMessage7);
	    } else
	    {
	      text += getResources().getString(R.string.strMessage8);
	      text += Math.abs(days);
	      text += getResources().getString(R.string.strMessage7);
	    }
	    txt_leftndays.setText(text);

	    //排卵日：下次MC来潮第一天起，倒数14天就是排卵期
	    txt_expnextodayval.setText(DateUtil.getNextDate(nDate, -14, format));
	  }
	
	public static final int MENU_ABOUT = Menu.FIRST;
	public static final int MENU_Quit = Menu.FIRST + 1;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ABOUT, 0, "关于").setIcon(R.drawable.ic_about);
		menu.add(0,MENU_Quit,0,"come on").setIcon(R.drawable.ic_out);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		super.onOptionsItemSelected(item);
		switch (item.getItemId()){
		    case MENU_ABOUT:
		    	openOptionsDialog();
		    	break;
		    case MENU_Quit:
		    	finish();
		    	break;
		}
		return true;
	}

	private void openOptionsDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
		dialog.setTitle(R.string.about_title);
		dialog.setMessage(R.string.about_msg);
		dialog.setPositiveButton(R.string.ok_label,
				new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						
					}
				});
		dialog.setNegativeButton(R.string.homepage_label,
				new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Uri uri = Uri.parse("http://273470570.qzone.qq.com");
						Intent intent = new Intent(Intent.ACTION_VIEW,uri);
						startActivity(intent);
					}
				});
		dialog.show();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_BACK){
			new AlertDialog.Builder(this)
			    .setTitle("确认")
			    .setMessage("Are you sure?")
			    .setNegativeButton("取消",
			    		new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
				.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								finish();
							}
						})
				.show();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());
	}

}
